package com.example.datamanage.utils;

import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

/**
 * @author 28142
 * @description jwt工具类
 * @date 2023/7/19 23:35
 */
public class JwtUtils {
    // 有效期
    private static final long JWT_EXPIRE = 30 * 60 * 1000L;
    // 令牌秘钥
    private static final String JWT_KEY = "YYS";

    /**
     * 生成token
     * @author 杨雨盛
     * @date 2023/7/19 23:39
     * @param data
     * @return java.lang.String
     */
    public static String createToken(Object data) {
        // 当前时间
        long currentTime = System.currentTimeMillis();
        // 过期时间
        long expireTime = currentTime + JWT_EXPIRE;
        // 构建jwt
        JwtBuilder builder = Jwts.builder()
                .setId(UUID.randomUUID() + "")
                .setSubject(JSON.toJSONString(data))
                .setIssuer("yys")
                .setIssuedAt(new Date(currentTime))
                .signWith(SignatureAlgorithm.HS256, encodeSecret(JWT_KEY))
                .setExpiration(new Date(expireTime));
        return builder.compact();
    }

    /**
     * 对令牌秘钥JWT_KEY进行Base64转码
     * @author 杨雨盛
     * @date 2023/7/19 23:39
     * @param key
     * @return javax.crypto.SecretKey
     */
    private static SecretKey encodeSecret(String key) {
        byte[] encode = Base64.getEncoder().encode((key.getBytes()));
        SecretKeySpec aes = new SecretKeySpec(encode, 0, encode.length, "AES");
        return aes;
    }

    /**
     * 解析toke
     * @author 杨雨盛
     * @date 2023/7/19 23:42
     * @param token
     * @return io.jsonwebtoken.Claims
     */
    public static Claims parseToken(String token) {
        Claims body = Jwts.parser()
                .setSigningKey(encodeSecret(JWT_KEY))
                .parseClaimsJws(token)
                .getBody();
        return body;
    }

    /**
     * 解析toke，返回存入的对象
     * @author 杨雨盛
     * @date 2023/7/19 23:43
     * @param token
     * @param clazz
     * @return T
     */
    public static <T> T parseToken(String token, Class<T> clazz) {
        Claims body = Jwts.parser()
                .setSigningKey(encodeSecret(JWT_KEY))
                .parseClaimsJws(token)
                .getBody();
        return JSON.parseObject((body.getSubject()), clazz);
    }
}
